<template>
  <div class="home_div">
    <div :id="id" class="container-map"></div>

    <div class="place" v-if="showSearch">
      <div class="place-label">搜索地点</div>
      <input class="place-input" id="tipinput" type="text" placeholder="请输入地址" />
      <div id="tipinputCon" class="place-con"></div>
    </div>

  </div>
</template>
<script setup>
import AMapLoader from '@amap/amap-jsapi-loader';
import { ref, onMounted, onUnmounted } from 'vue';
import dot from '@/assets/map/dot.png'
import head from '@/assets/map/head.png'
import start from '@/assets/map/start.png'
import end from '@/assets/map/end.png'


const id = ref('container' + Math.random());
let map = null;
const props = defineProps({
  showSearch: {
    type: Boolean,
    default: true
  },

})

const emit = defineEmits(['complete', 'click']);

onUnmounted(() => {
  map && map.destroy()
})

onMounted(async () => {
  await ininMap();
});

const getMask = () => {
  let opts = {
    subdistrict: 0,
    extensions: 'all',
    level: 'city'
  }
  return new Promise((resolve, reject) => {
    var district = new AMap.DistrictSearch(opts);
    district.search('柘荣县', function (status, result) {
      var bounds = result.districtList[0].boundaries;
      var mask = []
      for (var i = 0; i < bounds.length; i += 1) {
        mask.push([bounds[i]])
      }
      resolve(mask)
    })
  })
}


const ininMap = async () => {
  window._AMapSecurityConfig = {
    securityJsCode: "94f1eef588bd47b97115db71a380aa6a",
  };
  let AMap = await AMapLoader.load({
    key: '5d2226857772de272735f5e709a0db9b', //设置您的key
    version: '2.0',
    plugins: [
      'AMap.MouseTool',
      'AMap.PolygonEditor',
      'AMap.AutoComplete',
      'AMap.PlaceSearch',
      'AMap.PolyEditor',
      'AMap.DistrictSearch'
    ],
    AMapUI: {
      version: '1.1',
      plugins: [],
    },
    Loca: {
      version: '2.0.0',
    },
  });
  let mask = await getMask()
  map = new AMap.Map(id.value, {
    mask: mask,
    showLabel:false,
    pitch:40,
    viewMode: '3D',
    zoom: 12,
    zooms: [11, 22],
    center: [119.900493, 27.184325],

    layers: [
      // 卫星
      new AMap.TileLayer.Satellite(),
      // 路网
      new AMap.TileLayer.RoadNet()
    ],
    // center: [119.306582, 26.08332],
  });


  //输入提示
  var autoOptions = {
    input: 'tipinput',
    output: 'tipinputCon'
  };
  var auto = new AMap.AutoComplete(autoOptions);
  var placeSearch = new AMap.PlaceSearch({
    map: map,
  });

  AMap.Event.addListener(auto, 'select', select); //注册监听，当选中某条记录时会触发
  function select(e) {
    placeSearch.setCity(e.poi.adcode);
    placeSearch.search(e.poi.name); //关键字查询查询
  }

  map.on('click', (e) => {
    emit("click", e)
  });

  emit('complete', map);
};

const clearMap = () => {
  map.clearMap()
}

const addMarker = ({ img, width, height, lng, lat, anchor, content }) => {
  var icon = new AMap.Icon({
    size: new AMap.Size(width, height), // 图标尺寸
    image: img, // Icon的图像
    imageSize: new AMap.Size(width, height),
  });

  // 将 Icon 实例添加到 marker 上:
  var marker = new AMap.Marker({
    position: new AMap.LngLat(lng, lat),
    offset: new AMap.Pixel(0, 0), // 设置点标记偏移量
    anchor: anchor, // 设置锚点方位
    icon: icon, // 添加 Icon 实例
  });

  map.add(marker);
  return marker;
};
const addText = ({ lng, lat, content }) => {
  var text = new AMap.Text({
    text: content,
    anchor: 'top-center', // 设置文本标记锚点
    draggable: true,
    cursor: 'pointer',
    angle: 0,
    offset: new AMap.Pixel(0, 20),
    style: {
      'text-align': 'center',
    },
    position: [lng, lat],
  });

  text.setMap(map);
  return text;
};

const addPositionMarker = ({ lng, lat, content }) => {

  addMarker({
    img: dot,
    width: 30,
    height: 30,
    lng: lng,
    lat: lat,
    anchor: 'center'
  })

  addText({
    content: '' + content,
    lng: lng,
    lat: lat
  })

  addMarker({
    img: head,
    width: 66,
    height: 71,
    lng: lng,
    lat: lat,
    anchor: 'bottom-center'
  })

  map.setFitView();
}

const addPolyline = ({ path, color, isFitView }) => {
  let polyPath = path.map((obj) => {
    return [obj.lng, obj.lat];
  });

  var polygon = new AMap.Polyline({
    path: polyPath,
    strokeWeight: 8,
    strokeOpacity: 0.8,
    strokeColor: color,
    showDir: true,
  });

  map.add(polygon);
  if (isFitView) {
    map.setFitView();
  }

}



const drawTrack = ({ path }) => {


  var startMarker = addMarker({
    img: start,
    width: 23,
    height: 31,
    lng: path[0].lng,
    lat: path[0].lat,
    anchor: 'bottom-center',
  });

  var endMarker = addMarker({
    img: end,
    width: 23,
    height: 31,
    lng: path[path.length - 1].lng,
    lat: path[path.length - 1].lat,
    anchor: 'bottom-center',
  });

  let polyPath = path.map((obj) => {
    return [obj.lng, obj.lat];
  });

  var polygon = new AMap.Polyline({
    path: polyPath,
    strokeWeight: 8,
    strokeOpacity: 0.8,
    strokeColor: '#0091ea',
    showDir: true,
  });

  map.add(polygon);
  map.setFitView([polygon]);

  var res = addMarker({
    img: head,
    width: 66,
    height: 71,
    lng: path[0].lng,
    lat: path[0].lat,
    anchor: 'bottom-center',
  });

  res.moveAlong(polyPath, {
    // 每一段的时长
    duration: 500,//可根据实际采集时间间隔设置
    // JSAPI2.0 是否延道路自动设置角度在 moveAlong 里设置
    autoRotation: false,
  });
};

defineExpose({
  clearMap,
  ininMap, addMarker, addText, addPositionMarker, drawTrack, addPolyline,
})
</script>
<style scope>
.home_div {
  height: 100%;
  width: 100%;
  padding: 0px;
  margin: 0px;
  position: relative;
}

.container-map {
  height: 100%;
  width: 100%;
  padding: 0px;
  margin: 0px;
  background: #004b63 !important;
}

.map-title {
  position: absolute;
  z-index: 1;
  width: 100%;
  height: 50px;
  background-color: rgba(27, 25, 27, 0.884);
}

h3 {
  position: absolute;
  left: 10px;
  z-index: 2;
  color: white;
}


.place {
  position: absolute;
  z-index: 10;
  top: 10px;
  left: 20px;
  background: #fff;
  box-shadow: 0 0 5px 0 rgba(0, 0, 0, 0.5);
  padding: 10px 20px;
}

.place-con {
  position: absolute;
  width: 100%;
  background: #fff;
  top: 60px;
  left: 0;
  box-shadow: 0 0 5px 0 rgb(0 0 0 / 50%);
}

.place-label {
  width: 80px;
  display: inline-block;
  vertical-align: middle;
}

.place-input {
  display: inline-block;
  vertical-align: middle;
  width: 200px;
  padding: 5px 10px;
  border: 1px solid #d9d9d9;
}

.place-input:focus {
  outline: 1px solid #d9d9d9;
}
</style>
